package lowijs.XfireClient;

import java.util.*;

import lowijs.XfireClient.event.*;
import lowijs.XfireClient.util.*;

public class FriendManager implements XfireObserver {
	private final ArrayList<Friend> friends = new ArrayList<Friend>();
	private final ArrayList<Friend> onlineFriends = new ArrayList<Friend>();
	
	private static FriendManager fm = null;
	
	protected FriendManager() {
		EventManager.addObserver(this);
	}
	
	public static FriendManager getInstance() {
		if (fm == null)
			fm = new FriendManager();
		return fm;
	}
	
	public void cleanup() {
		EventManager.removeObserver(this);
		friends.clear();
		onlineFriends.clear();
		fm = null;
	}
	
	public synchronized void addFriend(Friend f) {
		friends.add(f);
	}
	
	public Friend getFriendByUserid(byte[] userid) {
		if (friends == null)
			return null;
		
		for (Friend f : friends) {
			if (Arrays.equals(f.getUserid(), userid))
				return f;
		}
		return null;
	}
	
	public Friend getFriendBySid(byte[] sid) {
		if (friends == null)
			return null;
		
		for (Friend f : friends) {
			if (Arrays.equals(f.getSid(), sid))
				return f;
		}
		return null;
	}
	
	public Friend getFriend(int pos) {
		return friends.get(pos);
	}
	
	public ArrayList<Friend> getFriends() {
		return friends;
	}
	
	public ArrayList<Friend> getOnlineFriends() {
		Collections.sort(onlineFriends, new FriendComparator());
		return onlineFriends;
	}
		
	public void handleEvent(XfireEvent event) {
		if (event.getEventType() == XfireEvent.XF_FRSTATUS) {
			Friend f = ((FriendStatusEvent)event).getFriend();
			if (f.isOnline())
				onlineFriends.add(f);
			else
				onlineFriends.remove(f);
		}
	}
}
